package fun.tan90.device.protocol;

import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;

import java.util.Map;

public class GraalDemo {


    public static void main(String[] args) {
        System.out.println("Graal Demo");
        try (Context context = Context.newBuilder()
                .allowAllAccess(true)
                .option("engine.WarnInterpreterOnly", "false")
                .build()) {

            String pySource = """
                    def main(name, age, scores=None, **kwargs) -> dict:
                        avg = sum(scores) / len(scores) if scores else 0
                        return {
                            'name': name.upper(),
                            'age': age + 1,
                            'average': avg,
                            'metadata': kwargs
                       }
                    """;

            Source pySrc = Source.create("python", pySource);

            System.out.println("Python source loaded");

            // 解析Python函数
            context.eval(pySrc);

            // 获取函数引用
            Value main = context.getBindings("python").getMember("main");
            System.out.println(main.canExecute());

            // 调用函数并传递参数
            Value result = main.execute(
                    "Bob",
                    25,
                    new int[]{88, 92, 72}
            );

            // 处理返回结果
            System.out.println("Result: " + result);
            Map<String, Object> map = result.as(Map.class);
            System.out.println("Result: " + map.get("name"));

            System.out.println("----------------------------------------------");

            String jsSource = """
                    function main(data) {
                      return {"name": data};
                    }
                    """;

            Source jsSrc = Source.create("js", jsSource);
            System.out.println("javascript source loaded");

            // 解析js函数
            context.eval(jsSrc);

            // 获取函数引用
            main = context.getBindings("js").getMember("main");
            System.out.println(main.canExecute());

            // 调用函数并传递参数
            result = main.execute("chj");
            // 处理返回结果
            System.out.println("Result: " + result);
            map = result.as(Map.class);
            System.out.println("Result: " + map.get("name"));
        }
    }
}
